<?php

namespace app\blogadmin\controller;

use think\Db;
use think\Request;
use app\blogadmin\model\Roles as RoleM;

class Role extends Base{
    /**
     * 角色列表
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */


    public function lst(){
        $roleM=new RoleM();
        $res=$roleM->getAllRole();
        $this->assign('role',$res);
        return $this->fetch();
    }

    public function add(){
        //获取权限列表
        $powerL=Db::table('admin_power')->where('status=1')->select();
        $powerLs =loop_tree($powerL);
        if(Request::instance()->isPost()){
            $data=input('post.');
            $data['tm']=time();
            $res=Db::table('admin_role')->insert($data);
            if($res){
                return json(['msg'=>'添加角色成功','code'=>'1']);
            }else {
                $this->error('');
                return json(['msg' => '添加角色失败', 'code' => '-1']);
            }
        }
        $this->assign('powerL',$powerLs);
        return $this->fetch();
    }

    /**
     * 修改角色信息
     * @return mixed|\think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function edit(){
        $id=Request::instance()->param('id');//获取当前id
        $cur_role=Db::table('admin_role')->find(['id'=>$id]); //获取当前用户信息
        $cur_role['power']=ltrim($cur_role['power'],',');
        //获取权限列表
        $powerL=Db::table('admin_power')->where('status=1')->select();
        $powerLs =loop_tree($powerL);

        dump($powerLs);die();
        if(Request::instance()->isPost()){
            $data=input("post.");
            $info['id']=htmlspecialchars($data['id']);
            $info['name']=htmlspecialchars($data['name']);
            $info['power']=htmlspecialchars($data['power']);
            $res=Db::table('admin_role')->update($info);
            if($res){
                return json(['code'=>1,'msg'=>"修改数据成功"]);
            }else{
                return json(['code'=>-1,'msg'=>"修改数据失败"]);
            }
        }
        $cur_power=explode(',', $cur_role['power']);
        $this->assign('cur_role',$cur_role);
        $this->assign('cur_power',$cur_power);
        $this->assign('powerL',$powerLs);
        return $this->fetch();
    }
    public function del(){
        if(Request::instance()->isPost()){
            $id=input('post.id');
            $res=Db::table('admin_role')->delete($id);
            if($res) {
                return json(['code'=>'1','msg'=>'删除数据成功']);
            }else {
                return json(['code'=>'0','msg'=>'删除数据失败']);
            }
        }
    }



}